import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite";
import { createVitePlugins } from "./build/plugins";
// import { createProxy } from "./build/proxy";
import { wrapperEnv } from "./build/getEnv";
import { resolve } from "path";
import pkg from "./package.json";
import dayjs from "dayjs";
const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
};

type ProxyConfigItem = {
  target: string;
  changeOrigin: boolean;
  secure?: boolean;
  rewrite?: (path: string) => string;
};

type ProxyConfig = {
  [key: string]: ProxyConfigItem;
};

// 示例用法
/*const proxyUrls: [string, string, string?][] = [
  ["/Demo", "https://10.77.76.66"],
  ["/Web", "http://192.168.43.228:30000"],
  ["/api", "https://mock.apifox.cn/m1/3037186-0-default"]
];
*/

function KProxy(proxyUrls: [string, string, string?][]): ProxyConfig {
  let urlList: ProxyConfig = {};

  if (Array.isArray(proxyUrls)) {
    proxyUrls.forEach(url => {
      if (Array.isArray(url) && url.length >= 2) {
        const [path, target, rewriteRule] = url;
        const httpsRE = /^https:\/\//;
        const isHttps = httpsRE.test(target);

        const proxyConfig: ProxyConfigItem = {
          target,
          changeOrigin: true,
          ...(isHttps ? { secure: false } : {})
        };

        proxyConfig.rewrite = (originalPath: string) => {
          const rewrittenPath = originalPath.replace(new RegExp(`^${path}`), rewriteRule || "");
          console.log(`Rewrite ${originalPath} to ${rewrittenPath}`);
          return rewrittenPath;
        };

        urlList[path] = proxyConfig;
      } else {
        console.error("代理配置错误，请检查:", url);
      }
    });
  } else {
    console.error("代理配置应为数组");
  }

  return urlList;
}

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  return {
    base: viteEnv.VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias: {
        "@": resolve(__dirname, "./src")
      }
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    },
    server: {
      // 注意，这里使用的是 server 而不是 devServer，因为 Vite 的配置中用的是 server
      headers: {
        "Access-Control-Allow-Credentials": "true" //支持携带凭证的请求
        /* "Access-Control-Allow-Origin": "http://localhost:9527", // 假设你的前端服务运行在这个地址
        "Access-Control-Allow-Headers": "X-Requested-With,Content-Type",
        "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS"*/
        // 'Content-Type': 'application/json; charset=utf-8' // 通常不需要在这里设置
      },
      host: "0.0.0.0",
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,
      cors: true,
      // Load proxy configuration from .env.development
      // proxy: createProxy(viteEnv.VITE_PROXY)
      proxy: KProxy(viteEnv.VITE_PROXY)
    },
    plugins: createVitePlugins(viteEnv),
    esbuild: {
      pure: viteEnv.VITE_DROP_CONSOLE ? ["console.log", "debugger"] : []
    },
    build: {
      outDir: "dist",
      minify: "esbuild",
      // esbuild is faster to package, but cannot remove console.log, terser is slower to package, but can remove console.log
      // minify: "terser",
      // terserOptions: {
      // 	compress: {
      // 		drop_console: viteEnv.VITE_DROP_CONSOLE,
      // 		drop_debugger: true
      // 	}
      // },
      sourcemap: false,
      // Disable gzip compressed size reporting, which slightly reduces pack time
      reportCompressedSize: false,
      // Determine the chunk size that triggers the warning
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          // Static resource classification and packaging
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
        }
      }
    }
  };
});
